//Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one
// sorted array. 
//
// The number of elements initialized in nums1 and nums2 are m and n respectivel
//y. You may assume that nums1 has a size equal to m + n such that it has enough s
//pace to hold additional elements from nums2. 
//
// 
// Example 1: 
// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
//Output: [1,2,2,3,5,6]
// Example 2: 
// Input: nums1 = [1], m = 1, nums2 = [], n = 0
//Output: [1]
// 
// 
// Constraints: 
//
// 
// nums1.length == m + n 
// nums2.length == n 
// 0 <= m, n <= 200 
// 1 <= m + n <= 200 
// -109 <= nums1[i], nums2[i] <= 109 
// 
// Related Topics 数组 双指针 
// 👍 951 👎 0


package leetcode.editor.cn;

//Java：Merge Sorted Array
class P88MergeSortedArray {
    public static void main(String[] args) {
        Solution solution = new P88MergeSortedArray().new Solution();
        // TO TEST
//        solution.merge(new int[]{1, 2, 4, 5, 6, 0}, 5, new int[]{3}, 1);
        solution.merge(new int[]{1, 2, 3, 0, 0, 0}, 6, new int[]{1, 2, 3}, 3);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public void merge(int[] nums1, int m, int[] nums2, int n) {
            if (n == 0) {
                return;
            }
            if (nums1 == null || nums1.length == 0) {
                return;
            }
            for (int i = nums1.length - 1; i >= n; i--) {
                nums1[i] = nums1[i - n];
            }
            int i = n;
            int j = 0;
            int index = 0;
            while (i < nums1.length || j < n) {
                if (i < nums1.length && j < n && nums1[i] < nums2[j]) {
                    nums1[index++] = nums1[i++];
                } else if (i < nums1.length && j < n && nums1[i] >= nums2[j]) {
                    nums1[index++] = nums2[j++];
                }
                if (i == nums1.length) {
                    nums1[index++] = nums2[j++];
                } else if (j == n) {
                    nums1[index++] = nums1[i++];
                }
            }
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}